package models

import (
	"time"
	"github.com/beego/beego/v2/client/orm"
	"errors"
)

//短信发送记录
type SmsSendLog struct {
	Id           int64
	Typeid       int
	DepartmentId int64
	Mobile       string
	VerifCode    string
	Content      string
	Status       int
	CreatedAt    int64
	CreatedBy    string
}

func SmsSendLogTableName() string {
	return TableName("sms_send_log")
}

func (m *SmsSendLog) TableName() string {
	return SmsSendLogTableName()
}

//增加发送日志
func (m *SmsSendLog) SmsInsert() error {
	m.CreatedAt = time.Now().Unix()
	if m.Typeid == 0 {
		m.Typeid = 2
	} else {
		m.Typeid = 1
	}

	if _, err := orm.NewOrm().Insert(m); err != nil {
		return err
	}
	return nil
}

//查询手机号当日发送次数
func SendSmsCount(mobile string) int64 {
	query := orm.NewOrm().QueryTable(SmsSendLogTableName())
	cond := orm.NewCondition()
	times := time.Now()
	start := time.Date(times.Year(), times.Month(), times.Day(), 0, 0, 0, 0, time.Local).Unix()
	end := time.Date(times.Year(), times.Month(), times.Day(), 22, 59, 59, 0, time.Local).Unix()
	cond = cond.And("status", 1).And("mobile", mobile).And("created_at__gte", start).And("created_at__lte", end)
	query = query.SetCond(cond)
	count, _ := query.Count()
	return count
}

//验证手机验证码有效性
func CheckSmsVerifCodeValid(mobile, verif_code string) error {
	m := &SmsSendLog{}
	err := orm.NewOrm().QueryTable(SmsSendLogTableName()).Filter("typeid", 1).Filter("status", 1).Filter("mobile", mobile).Filter("verif_code", verif_code).OrderBy("-id").One(m)
	if err != nil {
		return errors.New("验证码不存在") //SQL执行出错
	}
	if m.Id == 0 {
		return errors.New("验证码不存在") //没有找到验证码
	}
	//验证时间超时30分钟，判断为失效
	cut := time.Now().Unix() - m.CreatedAt
	if cut >= 1800 {
		//return errors.New("验证码已超时")
	}
	return nil //默认有效
}
